package top.xtcoder.jdcbase.rbac.service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.beetl.sql.core.SQLManager;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import cn.hutool.core.collection.CollectionUtil;
import top.xtcoder.jdcbase.base.core.UserLoginOpType;
import top.xtcoder.jdcbase.base.core.UserType;
import top.xtcoder.jdcbase.base.entity.base.AccountInfo;
import top.xtcoder.jdcbase.base.redis.RedisCache;
import top.xtcoder.jdcbase.base.service.AccountService;
import top.xtcoder.jdcbase.base.vo.auth.LoginResult;
import top.xtcoder.jdcbase.base.vo.auth.PwdLoginVo;
import top.xtcoder.jdcbase.rbac.entity.AdminInfo;
import top.xtcoder.jdcbase.rbac.entity.Permission;
import top.xtcoder.jdcbase.rbac.vo.MenuLoginResult;
import top.xtcoder.jdcbase.rbac.vo.PermVo;

@Service
public class PbRbacAccountService extends AccountService{
	@Autowired
	private Dao dao;
	
	@Autowired
	private SQLManager sqlManager;
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	@Autowired
	private RedisCache redisCache;
	
	@Autowired
	private PbRbacPermissionService permissionService;
	
	public <T extends AccountInfo> MenuLoginResult pwdLogin2(int type, Class<T> table, HttpServletRequest request,
			PwdLoginVo dto) throws Exception {
		LoginResult lr = super.pwdLogin(type, table, request, dto);
		MenuLoginResult result = new MenuLoginResult();
		Lang.copyProperties(lr, result);
		
		NutMap permMap = permissionService.getPermSetByUserid(type, result.getAccountInfo().getId());
		Set<String> permIds = permMap.getAs("permIds", Set.class);
		Map<String, List<String>> permBtnMap = permMap.getAs("permBtnMap", Map.class);
		List<PermVo> permVo = permissionService.loadLeftMenu(permIds, permBtnMap, "0");
		result.setMenus(permVo);
		
		String loginSuccessUrl = getLoginSuccessUrl(result.getAccountInfo().getId());
		result.setLoginSuccessUrl(loginSuccessUrl);
		
		return result;
	}
	
	private String getLoginSuccessUrl(String adminid) {
		String queryLoginSuccessUrl = sqlManager.selectSingle("prrbac.account.queryLoginSuccessUrl", NutMap.NEW().addv("adminid", adminid), String.class);
		return queryLoginSuccessUrl;
	}
}